# coding:utf-8
from flask import Flask
app = Flask(__name__)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

import ujson
import role_mgr

# http params -> json
# 解压post的数据p
def parse_params_raw(request, key='p'):
    v = ''
    if request.method == 'POST':
        v = request.form[key]
    else:
        v = request.args.get(key, '')

    print "params[%s]:%s" % (key, v)

    if v == '': return None

    res = None
    try:
        res = ujson.loads(v)
    except Exception, e:
        glog.log('glb>parse_params 发送的参数错误 key:%s value:%s' % (key, v))
    return res


# 解压数据,并转成account和role
def parse_params(request):
    import login
    params = parse_params_raw(request)
    session_key = int(parse_params_raw(request, 'sk'))    # session_key
    d = login.get_account_and_role_id(session_key)
    account = d[0]
    role_id = d[1]
    role = None
    if role_id != None:
        role = role_mgr.get(role_id)
    return [params, account, role]


# 发送数据打包
def packs(data):
    return ujson.dumps(data)


def return_cmd(cmd):
    return packs({'cmd':cmd})


def return_msg(msg):
    return packs({'msg':msg})


def return_ok(data=None, cmd=None):
    res = {'result':'ok'}
    if(data != None): res['data']=data
    if(cmd != None): res['cmd']=cmd
    return packs(res)


def return_err(errmsg, cmd=None):
    res = {'err':errmsg}
    if(cmd != None): res['cmd']=cmd
    return packs(res)


# battle -------------------------
# 战斗站位
BATTLE_SIDE_A = 0
BATTLE_SIDE_B = 1

# 战斗结果
BATTLE_RESULT_WIN = 0
BATTLE_RESULT_LOSE = 1
BATTLE_RESULT_DRAW = 2

# 战斗数据中的事件类型
BATTLE_DATA_EVENT_ATTACK = 'A'
BATTLE_DATA_EVENT_MOVE = 'M'

# 每秒帧数
BATTLE_FRAME_PER_SECOND = 5

